package github.leavesczy.wififiletransfer.receiver

import android.Manifest
import android.content.Context
import android.net.ConnectivityManager
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import coil.load
import com.android.dx.stock.ProxyBuilder
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import github.leavesczy.wififiletransfer.BaseActivity
import github.leavesczy.wififiletransfer.MediaFileUtil
import github.leavesczy.wififiletransfer.R
import github.leavesczy.wififiletransfer.models.ViewState
import kotlinx.coroutines.launch
import java.lang.reflect.InvocationHandler
import java.security.AccessController.getContext

class FileReceiverActivity : BaseActivity() {

    private val fileReceiverViewModel by viewModels<FileReceiverViewModel>()

    private val tvState by lazy {
        findViewById<TextView>(R.id.tvState)
    }

    private val btnStartReceive by lazy {
        findViewById<Button>(R.id.btnStartReceive)
    }
    private val btnHost by lazy {
        findViewById<Button>(R.id.btnHost)
    }

    private val ivImage by lazy {
        findViewById<ImageView>(R.id.ivImage)
    }
    private val tvFile by lazy {
        findViewById<TextView>(R.id.tvFile)
    }
    private val progressBar by lazy {
        findViewById<ProgressBar>(R.id.pb)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file_receiver)
        supportActionBar?.title = "文件接收端"
        btnStartReceive.setOnClickListener {
            tvState.text = ""
            ivImage.load(data = null)
            fileReceiverViewModel.startListener()
        }
        btnHost.setOnClickListener {
            startTethering(this)
        }
        initEvent()
        getPermissions()
    }

    private fun initEvent() {
        lifecycleScope.launch {
            fileReceiverViewModel.viewState.collect {
                when (it) {
                    ViewState.Idle -> {
                        tvState.text = ""
                        dismissLoadingDialog()
                    }

                    ViewState.Connecting -> {
                        showLoadingDialog()
                    }

                    is ViewState.Receiving -> {
                        showLoadingDialog()
                    }

                    is ViewState.Success -> {
                        dismissLoadingDialog()
                        val b = MediaFileUtil.isImageFileType(it.file.path)
                        if (b) {
                            tvFile.visibility = View.GONE
                            ivImage.visibility = View.VISIBLE
                            ivImage.load(data = it.file)
                        } else {
                            tvFile.visibility = View.VISIBLE
                            ivImage.visibility = View.GONE
                            tvFile.text = it.file.name
                        }
                    }

                    is ViewState.Failed -> {
                        dismissLoadingDialog()
                    }
                }
            }
        }
        lifecycleScope.launch {
            fileReceiverViewModel.log.collect {
                tvState.append(it)
                tvState.append("\n\n")
            }
        }
        fileReceiverViewModel.progressData.observe(this) {
            progressBar.progress = it
        }
    }

    private fun getPermissions() {
        XXPermissions.with(this)
            .permission(
                Manifest.permission.WRITE_SETTINGS,
                Permission.MANAGE_EXTERNAL_STORAGE)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, all: Boolean) {
                    if (!all) {
                        Toast.makeText(this@FileReceiverActivity, "请授予权限", Toast.LENGTH_LONG).show()
                        return
                    }
                }

                override fun onDenied(permissions: MutableList<String>, never: Boolean) {
                    if (never) {
                        Toast.makeText(
                            this@FileReceiverActivity,
                            "被永久拒绝授权，请手动授予权限",
                            Toast.LENGTH_LONG
                        ).show()
                    } else {
                        Toast.makeText(this@FileReceiverActivity, "获取权限失败", Toast.LENGTH_LONG)
                            .show()
                    }
                }
            })
    }

    /**
     * 打开WiFi热点
     * @param context
     */
    fun startTethering(context: Context) {
        //1、环境属性记录
        val property = System.getProperty("dexmaker.dexcache")

        //2、设置新的属性
        System.setProperty("dexmaker.dexcache", context.cacheDir.path)

        //3、反射操作打开热点
        val connectivityManager =
            context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
        try {
            val classOnStartTetheringCallback =
                Class.forName("android.net.ConnectivityManager\$OnStartTetheringCallback")
            val startTethering = connectivityManager.javaClass.getDeclaredMethod(
                "startTethering",
                Int::class.javaPrimitiveType,
                Boolean::class.javaPrimitiveType, classOnStartTetheringCallback
            )
            val proxy: Any = ProxyBuilder.forClass(classOnStartTetheringCallback).handler(
                InvocationHandler { o, method, objects -> null }).build()
            startTethering.invoke(connectivityManager, 0, false, proxy)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        //4、恢复环境属性
        if (property != null) {
            System.setProperty("dexmaker.dexcache", property)
        }
    }

}